
#include "stdafx.h"
#include "xcpctrl_h.h"
#include "xcpctrl_i.c"
#include "host.h"

class CLoAgWindow :
	public IOleClientSite,
	public IOleInPlaceSiteWindowless,
	public IOleControlSite,
	public IObjectWithSite,
	public IOleContainer,
	public IServiceProvider,
	public IXcpControlHost3
{
public:
	CLoAgWindow()
	{
		iXcpControl2_ = NULL;
	}
	~CLoAgWindow()
	{
		destroy();
	}
	/** This creates the window, which is resized to fit the silver light control
	*/
	HRESULT create( HWND parent, LPCWSTR source, PHANDLE handle )
	{
		HRESULT	hErr = E_UNEXPECTED;

		do
		{
			if( FAILED(hErr = destroy()))
			{
				break;
			}
			if( FAILED(hErr = StgCreateDocfile( 0, STGM_READWRITE | STGM_SHARE_EXCLUSIVE | STGM_DIRECT | STGM_CREATE, 0, &iStorage_ )) )
			{	// Creates a temporary file we can use for storage.
				break;
			}
			if( FAILED(hErr = OleCreate( CLSID_XcpControl, IID_IOleObject, OLERENDER_DRAW, 0, (IOleClientSite *)this, (IStorage *)this, (void **)&iOleObject_)) )
			{	// Creates the AgControl.AgControl object but returns the IOleObject interface
				break;
			}
		} while(false);
		return hErr;
	}
	HRESULT destroy()
	{
		if( NULL == iXcpControl2_ )
		{
			iXcpControl2_->Release();
			iXcpControl2_ = NULL;
		}
		if( NULL == iStorage_ )
		{
			iStorage_->Release();
			iStorage_ = NULL;
		}
		return S_OK;
	}
private:
	IXcpControl2		*iXcpControl2_;			// Main interface to the object
	ISilverlightViewer	*iSilverlightViewer_;
	HWND				hwnd_;					// Window Handle
	IOleObject			*iOleObject_;
	IStorage			*iStorage_;
};

/*!
\brief Creates an application based on a .xap file.

It gets all its parameters from the source file.
@param[in]	parent	Parent application
@param[in]	source	Path to source file to run
@param[out]	handle	Handle to the window
\retval HRESULT
*/
HRESULT LoAgWindowCreate( HWND parent, LPCWSTR source, PHANDLE handle )
{
	HRESULT	hErr = E_UNEXPECTED;

	//*handle = (HANDLE)(new CLoAgWindow());
	//((CLoAgWindow *)*handle)->create( source );

	return hErr;
}

HRESULT LoAgWindowDestroy( HANDLE handle )
{
	if( handle )
	{
		delete (CLoAgWindow *)handle;
	}
	return S_OK;
}
